import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const Login = ()=>import('../views/Login')
const Layout = ()=>import('../views/Layout')
const Home = ()=>import('../views/Home')
const Menu = ()=>import('../views/Menu/index.vue')
const Role = ()=>import('../views/Role/index.vue')
const Admin = ()=>import('../views/Admin/index.vue')
const Category = ()=>import('../views/Category/index.vue')
const Specs = ()=>import('../views/Specs/index.vue')
const Goods = ()=>import('../views/Goods/index.vue')
const Seckill = ()=>import('../views/Seckill/index.vue')
const Member = ()=>import('../views/Member/index.vue')
const Banner = ()=>import('../views/Banner/index.vue')
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '', // 默认的子路由
        component: Home,
        meta: {
          title: '主页'
        }
      },
      {
        path: 'menu',
        component: Menu,
        meta: {
          title: '菜单'
        }
      },
      {
        path: 'role',
        component: Role,
        meta: {
          title: '角色'
        }
      },
      {
        path: 'admin',
        component: Admin,
        meta: {
          title: '管理员'
        }
      },
      {
        path: 'category',
        component: Category,
        meta: {
          title: '商品分类'
        }
      },
      {
        path: 'specs',
        component: Specs,
        meta: {
          title: '商品规格'
        }
      },
      {
        path: 'goods',
        component: Goods,
        meta: {
          title: '商品管理'
        }
      },
      {
        path: 'seckill',
        component: Seckill,
        meta: {
          title: '秒杀活动'
        }
      },
      {
        path: 'member',
        component: Member,
        meta: {
          title: '会员管理'
        }
      },
      {
        path: 'banner',
        component: Banner,
        meta: {
          title: '轮播图管理'
        }
      }
    ]
  },
  {
    path: '/login',
    component: Login,
    meta: {
      title: '登录'
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  // base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 统一增加title
  document.title = to.meta.title;
  // 如果登录了，就正常跳转；没有登录还想去其他页面，就跳转回登录页
  let info = JSON.parse(localStorage.getItem('userInfo'));
  if(info) {
    // 已经登录了
    next();
  }else {
    // 未登录
    if(to.path === '/login') {
      // 可以去登录页面
      next();
    }else {
      // 不可以去其他页面
      next('/login');
    }
  }
})

export default router
